﻿using AutoMapper;
using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Write.API.Application.Commands.MessageCommand;
using D.Medicalcare.Write.API.Application.Commands.PatientCommand;
using D.Medicalcare.Write.API.Application.Handlers.PatientHandler;
using MediatR;

namespace D.Medicalcare.Write.API.Application.Handlers.MessageHandler
{
    public class CreateMessageHandler : IRequestHandler<CreateMessageCommand, APIResult<object>>
    {
        private readonly IMapper mapper;
        private readonly IBaseRepository<Message> mrep;
        private readonly ILogger<CreateMessageHandler> logger;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="mapper">映射</param>
        /// <param name="logger">日志</param>
        public CreateMessageHandler(IMapper mapper, IBaseRepository<Message> mrep, ILogger<CreateMessageHandler> logger)
        {
            this.mapper = mapper;
            this.mrep = mrep;
            this.logger = logger;
        }
        /// <summary>
        /// 处理
        /// </summary>
        public Task<APIResult<object>> Handle(CreateMessageCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            try
            {
                var map = mapper.Map<Message>(request);
                    map.IsDeleted=false;
                    var a = mrep.AddAsync(map).Result;
                    var model = mrep.GetAll().FirstOrDefault(x => x.Title == request.Title);
                    if (a > 0)
                    {
                        result.Code = APIEnum.Success;
                        result.Msg = "添加成功";
                        result.Data = model;
                        logger.LogInformation("添加消息公告成功");
                    }
                    else
                    {
                        result.Code = APIEnum.Failed;
                        result.Msg = "添加失败";
                        result.Data = model;
                        logger.LogError("添加消息公告失败");
                    }
                

                return Task.FromResult(result);
            }
            catch (Exception ex)
            {
                logger.LogError("添加消息公告异常" + ex.Message);
                throw;
            }
        }
    }
}

